package com.ac.api.component.controller;

import com.base.annotation.Unsecured;
import com.base.context.Context;
import com.base.context.ContextHolder;
import com.base.helper.DateUtils;
import com.base.helper.FileUploadUtils;
import com.ac.api.component.dao.CpAttachmentMapper;
import com.ac.api.component.dao.CpPhotoMapper;
import com.ac.api.component.vo.CpAttachmentVo;
import com.ac.api.component.vo.CpPhotoVo;
import org.springframework.web.bind.annotation.RequestMapping;
import com.base.annotation.SysLog;
import org.springframework.web.bind.annotation.RestController;
import com.base.helper.BaseController;
import com.base.helper.Result;
import com.ac.api.component.entity.CpPhoto;
import com.ac.api.component.service.CpPhotoService;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author gjj
 * @since 2024-10-26
 */
@Api(tags = "图片管理")
@RestController
@RequestMapping("/cpPhoto")
public class CpPhotoController extends BaseController {

        private static final Logger       LOG = LoggerFactory.getLogger(CpPhotoController.class);
        @Autowired
        private              CpPhotoService entityService;
        @Autowired
        private CpPhotoMapper cpPhotoMapper;
        @Autowired
        private CpAttachmentMapper cpAttachmentMapper;

        @SysLog(action = "findByPage", value = "分页查询图片")
        @ApiOperation(value = "分页查询图片", notes = "分页查询图片")
        @RequestMapping(method = RequestMethod.GET)
        @ApiImplicitParams({@ApiImplicitParam(name = "size", value = "分页大小", paramType = "query"),
                @ApiImplicitParam(name = "current", value = "当前页面：从1开始", paramType = "query")})
        public Result<IPage<CpPhoto>> findByPage(final CpPhotoVo example, final Page page) {
            IPage<CpPhotoVo>        records    = entityService.findByPage(example,page);
            return new Result(true, records);
        }

        @SysLog(action = "delete", value = "删除图片")
        @ApiOperation(value = "删除图片")
        @RequestMapping(value = "{id}", method = {RequestMethod.DELETE})
        @ApiImplicitParam(name = "id", value = "图片ID", required = true, paramType = "path")
        public Result delete(@PathVariable final Integer id) {
            try {
                entityService.deletePhotoById(id);
                return new Result(true, "成功删除图片", null);
            } catch (DataIntegrityViolationException e) {
                LOG.error("删除图片失败", e);
                return new Result(false, "删除图片失败", "该图片不能删除，存在其他关联数据");
            } catch (Exception e) {
                LOG.error("删除图片失败", e);
                return new Result(false, "删除图片失败", e.getMessage());
            }
        }

//        @SysLog(action = "one", value = "查询单个图片")
//        @ApiOperation(value = "查询单个图片")
//        @RequestMapping(value = "{id}", method = {RequestMethod.GET})
//        @ApiImplicitParam(name = "id", value = "图片ID", required = true, paramType = "path")
//        public Result one(@PathVariable final Integer id) {
//            try {
//                CpPhotoVo entity = cpPhotoMapper.findPhotoById(id);
//                return new Result(true, entity);
//            } catch (Exception e) {
//                LOG.error("查询单个图片失败", e);
//                return new Result(false, new CpPhoto());
//            }
//        }

        @SysLog(action = "one", value = "查询单个附件")
        @ApiOperation(value = "查询单个附件")
        @RequestMapping(value = "{id}", method = {RequestMethod.GET})
        @ApiImplicitParam(name = "id", value = "附件ID", required = true, paramType = "path")
        public Result one(@PathVariable final Integer id) {
            try {
                CpAttachmentVo entity = cpAttachmentMapper.findAttachmentById(id);
                return new Result(true, entity);
            } catch (Exception e) {
                LOG.error("查询单个图片失败", e);
                return new Result(false, new CpPhoto());
            }
        }

        @SysLog(action = "add", value = "添加图片")
        @ApiOperation(value = "添加图片")
        @RequestMapping(method = {RequestMethod.POST})
        public Result add(@Valid @RequestBody final CpPhotoVo entity,final BindingResult result) {
            try {
                if (result.hasErrors()) {
                    Map<String, String> map      = this.getErrors(result);
                    String              errorMsg = map.entrySet().iterator().next().getValue();
                    return new Result(false, "保存图片失败", errorMsg, map);
                } else {
                    CpPhotoVo cpPhotoVo=entityService.savePhoto(entity);
                    if (null == cpPhotoVo) {
                        return new Result(false, "","无法找到对应模块和标签");
                    }
                    return new Result(true, "成功保存图片", null);
                }
            } catch (Exception e) {
                LOG.error("添加图片失败", e);
                return new Result(false, "保存图片失败", e.getMessage());
            }
        }

        @SysLog(action = "update", value = "修改图片")
        @ApiOperation(value = "修改图片")
        @RequestMapping(method = {RequestMethod.PUT})
        public Result update(@Valid @RequestBody final CpPhotoVo entity, final BindingResult result) {
            try {
                if (result.hasErrors()) {
                    Map<String, String> map      = this.getErrors(result);
                    String              errorMsg = map.entrySet().iterator().next().getValue();
                    return new Result(false, "修改图片失败", errorMsg, map);
                } else {
                    if (null == entity.getId()) {
                         throw new RuntimeException("id不能为空");
                    }
                    CpPhotoVo cpPhotoVo=entityService.updatePhoto(entity);
                    if (null == cpPhotoVo) {
                        return new Result(false, "","无法找到对应模块和标签");
                    }
                    return new Result(true, "成功修改图片", null);
                }
            } catch (Exception e) {
                LOG.error("修改图片失败", e);
                return new Result(false, "修改图片失败", e.getMessage());
            }
        }



        @ApiOperation(value = "根据标签id查询全部图片")
        @RequestMapping(value = "all", method = RequestMethod.GET)
        @Unsecured
        public Result<List<CpPhoto>> all(Integer labelId) {
            List<CpPhoto> entitys = entityService.lambdaQuery()
                    .eq(CpPhoto::getState,"t")
                    .eq(CpPhoto::getCpLabelId,labelId).list();
            if (null != entitys) {
                return new Result<>(true, entitys);
            }
            return new Result<>(true, Collections.emptyList());
        }

    @Unsecured
    @ApiOperation(value = "公开图片上传,返回图片id")
    @RequestMapping(value = "uploadPictrue", method = RequestMethod.POST)
    public Result<CpPhoto> uploadPictrue(@RequestParam("file") MultipartFile file) {
        String  oriname = file.getOriginalFilename();
        try {
            String convertedName = new String(oriname.getBytes("ISO8859_1"), "UTF-8");
            long   size          = file.getSize();
            LOG.info("原文件名：{}, 大小: {}", convertedName, size);
            //
            String code     = UUID.randomUUID().toString().replaceAll("-", "");
            String filePath = FileUploadUtils.uploadFile(file, "picture"+"\\"+ DateUtils.date(new Date(), "yyyyMMdd"), code);
            if (null == filePath) {
                throw new RuntimeException("保存文件失败");
            }
            Context context = ContextHolder.currentContext();
            CpPhoto cpPhoto = new CpPhoto();
            cpPhoto.setUserid(context.currentUser().getId());
            cpPhoto.setName(convertedName);
            cpPhoto.setPath(filePath);
            cpPhoto.setSize(size + "");
            cpPhoto.setCreatetime(new Date());
            cpPhoto.setState("t");
            entityService.save(cpPhoto);
            return new Result(true, cpPhoto);
        } catch (Exception e) {
            LOG.error("保存文件失败", e);
            return new Result(false, "上传文件失败", e.getMessage());
        }
    }

}

